package com.lmabbe.common.mvc.core.qiniu;

import com.lmabbe.common.global.constant.RedisKeyConstant;
import com.lmabbe.common.global.constant.SysParamConstant;
import com.lmabbe.common.global.context.LmabbeMetadata;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * 七牛云AccessToken认证处理
 *
 * @author lmabbe
 */
@Slf4j
@Component
public class AccessTokenHandler {

    @Autowired
    private LmabbeMetadata lmabbeMetadata;

    /**
     * 获取AccessToken
     *
     * @return {@link String}
     * @date 2022/1/7 11:26 AM
     * @author liming
     */
    @Cacheable(value = RedisKeyConstant.System.Oss.ACCESS_TOKEN+"#3600", keyGenerator = "ossAccessTokenGenerator")
    public String getAccessToken() {
        Auth auth = Auth.create(lmabbeMetadata.getParamByKey(SysParamConstant.SYS_OSS_ACCESS),
                lmabbeMetadata.getParamByKey(SysParamConstant.SYS_OSS_SECRET));
        return auth.uploadToken(lmabbeMetadata.getParamByKey(SysParamConstant.SYS_OSS_BUCKET));
    }


    /**
     * key的生成器
     *
     * @return {@link KeyGenerator}
     * @date 2022/1/7 11:58 AM
     * @author liming
     */
    @Bean
    public KeyGenerator ossAccessTokenGenerator() {
        return (o, method, objects) ->
                lmabbeMetadata.getParamByKey(SysParamConstant.SYS_OSS_ACCESS)
                        + ":" +
                        lmabbeMetadata.getParamByKey(SysParamConstant.SYS_OSS_BUCKET);
    }
}
